import axios from 'axios'

// 创建axios实例
const api = axios.create({
  baseURL: process.env.VUE_APP_API_BASE_URL || 'http://localhost:3000/api',
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json'
  }
})

// 请求拦截器
api.interceptors.request.use(
  config => {
    // 添加token到请求头
    const token = localStorage.getItem('token')
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// 响应拦截器
api.interceptors.response.use(
  response => {
    return response.data
  },
  error => {
    if (error.response?.status === 401) {
      // token过期，跳转到登录页
      localStorage.removeItem('token')
      localStorage.removeItem('userInfo')
      window.location.href = '#/login'
    }
    return Promise.reject(error)
  }
)

// 用户相关API
export const userAPI = {
  // 登录
  login: (data) => api.post('/auth/login', data),
  
  // 获取用户信息
  getUserInfo: () => api.get('/user/info'),
  
  // 更新用户信息
  updateUserInfo: (data) => api.put('/user/info', data),
  
  // 修改密码
  changePassword: (data) => api.put('/user/password', data),
  
  // 上传头像
  uploadAvatar: (file) => {
    const formData = new FormData()
    formData.append('avatar', file)
    return api.post('/user/avatar', formData, {
      headers: { 'Content-Type': 'multipart/form-data' }
    })
  }
}

// 套餐管理API
export const comboAPI = {
  // 获取套餐列表
  getCombos: (params) => api.get('/combos', { params }),
  
  // 添加套餐
  addCombo: (data) => api.post('/combos', data),
  
  // 更新套餐
  updateCombo: (id, data) => api.put(`/combos/${id}`, data),
  
  // 删除套餐
  deleteCombo: (id) => api.delete(`/combos/${id}`),
  
  // 获取套餐详情
  getComboDetail: (id) => api.get(`/combos/${id}`)
}

// 健康管理API
export const healthAPI = {
  // 获取健康记录
  getHealthRecords: (params) => api.get('/health/records', { params }),
  
  // 添加健康记录
  addHealthRecord: (data) => api.post('/health/records', data),
  
  // 更新健康记录
  updateHealthRecord: (id, data) => api.put(`/health/records/${id}`, data),
  
  // 删除健康记录
  deleteHealthRecord: (id) => api.delete(`/health/records/${id}`),
  
  // 获取健康概览
  getHealthOverview: () => api.get('/health/overview'),
  
  // 获取用药提醒
  getMedicationReminders: () => api.get('/health/medication-reminders'),
  
  // 添加用药提醒
  addMedicationReminder: (data) => api.post('/health/medication-reminders', data),
  
  // 更新用药提醒
  updateMedicationReminder: (id, data) => api.put(`/health/medication-reminders/${id}`, data),
  
  // 删除用药提醒
  deleteMedicationReminder: (id) => api.delete(`/health/medication-reminders/${id}`)
}

// 生活管理API
export const lifeAPI = {
  // 获取日程安排
  getSchedules: (params) => api.get('/life/schedules', { params }),
  
  // 添加日程
  addSchedule: (data) => api.post('/life/schedules', data),
  
  // 更新日程
  updateSchedule: (id, data) => api.put(`/life/schedules/${id}`, data),
  
  // 删除日程
  deleteSchedule: (id) => api.delete(`/life/schedules/${id}`),
  
  // 获取生活提醒
  getLifeReminders: () => api.get('/life/reminders'),
  
  // 添加生活提醒
  addLifeReminder: (data) => api.post('/life/reminders', data),
  
  // 获取生活记录
  getLifeRecords: (params) => api.get('/life/records', { params }),
  
  // 添加生活记录
  addLifeRecord: (data) => api.post('/life/records', data)
}

// 数据分析API
export const analyticsAPI = {
  // 获取数据概览
  getDataOverview: () => api.get('/analytics/overview'),
  
  // 获取健康趋势数据
  getHealthTrends: (params) => api.get('/analytics/health-trends', { params }),
  
  // 获取健康评估报告
  getHealthAssessment: () => api.get('/analytics/health-assessment'),
  
  // 获取活动分析
  getActivityAnalysis: (params) => api.get('/analytics/activity', { params }),
  
  // 获取睡眠分析
  getSleepAnalysis: (params) => api.get('/analytics/sleep', { params }),
  
  // 导出数据
  exportData: (type, format) => api.get(`/analytics/export/${type}/${format}`, {
    responseType: 'blob'
  })
}

// 人工服务API
export const artificialAPI = {
  // 获取服务申请列表
  getServiceApplications: (params) => api.get('/artificial/applications', { params }),
  
  // 提交服务申请
  submitApplication: (data) => api.post('/artificial/applications', data),
  
  // 更新申请
  updateApplication: (id, data) => api.put(`/artificial/applications/${id}`, data),
  
  // 取消申请
  cancelApplication: (id) => api.delete(`/artificial/applications/${id}`),
  
  // 评价服务
  rateService: (id, data) => api.post(`/artificial/applications/${id}/rating`, data),
  
  // 获取服务类型
  getServiceTypes: () => api.get('/artificial/service-types')
}

// 安全管理API
export const securityAPI = {
  // 获取登录记录
  getLoginRecords: (params) => api.get('/security/login-records', { params }),
  
  // 更新安全设置
  updateSecuritySettings: (data) => api.put('/security/settings', data),
  
  // 获取安全设置
  getSecuritySettings: () => api.get('/security/settings'),
  
  // 添加紧急联系人
  addEmergencyContact: (data) => api.post('/security/emergency-contacts', data),
  
  // 更新紧急联系人
  updateEmergencyContact: (id, data) => api.put(`/security/emergency-contacts/${id}`, data),
  
  // 删除紧急联系人
  deleteEmergencyContact: (id) => api.delete(`/security/emergency-contacts/${id}`),
  
  // 获取紧急联系人列表
  getEmergencyContacts: () => api.get('/security/emergency-contacts'),
  
  // 导出用户数据
  exportUserData: () => api.get('/security/export-data', { responseType: 'blob' }),
  
  // 删除账户
  deleteAccount: (data) => api.post('/security/delete-account', data)
}

// 公告管理API
export const announcementAPI = {
  // 获取公告列表
  getAnnouncements: (params) => api.get('/announcements', { params }),
  
  // 获取公告详情
  getAnnouncementDetail: (id) => api.get(`/announcements/${id}`),
  
  // 标记已读
  markAsRead: (id) => api.post(`/announcements/${id}/read`),
  
  // 标记全部已读
  markAllAsRead: () => api.post('/announcements/read-all'),
  
  // 收藏公告
  favoriteAnnouncement: (id) => api.post(`/announcements/${id}/favorite`),
  
  // 取消收藏
  unfavoriteAnnouncement: (id) => api.delete(`/announcements/${id}/favorite`),
  
  // 获取收藏列表
  getFavorites: () => api.get('/announcements/favorites')
}

// 病例记录API（后台管理）
export const medicalRecordAPI = {
  // 获取病例记录列表
  getMedicalRecords: (params) => api.get('/admin/medical-records', { params }),
  
  // 添加病例记录
  addMedicalRecord: (data) => api.post('/admin/medical-records', data),
  
  // 更新病例记录
  updateMedicalRecord: (id, data) => api.put(`/admin/medical-records/${id}`, data),
  
  // 删除病例记录
  deleteMedicalRecord: (id) => api.delete(`/admin/medical-records/${id}`),
  
  // 获取病例详情
  getMedicalRecordDetail: (id) => api.get(`/admin/medical-records/${id}`),
  
  // 添加治疗记录
  addTreatmentRecord: (recordId, data) => api.post(`/admin/medical-records/${recordId}/treatments`, data),
  
  // 归档病例
  archiveMedicalRecord: (id) => api.put(`/admin/medical-records/${id}/archive`),
  
  // 打印病例
  printMedicalRecord: (id) => api.get(`/admin/medical-records/${id}/print`, { responseType: 'blob' })
}

// 病例档案API（后台管理）
export const medicalFileAPI = {
  // 获取病例档案列表
  getMedicalFiles: (params) => api.get('/admin/medical-files', { params }),
  
  // 添加病例档案
  addMedicalFile: (data) => api.post('/admin/medical-files', data),
  
  // 更新病例档案
  updateMedicalFile: (id, data) => api.put(`/admin/medical-files/${id}`, data),
  
  // 删除病例档案
  deleteMedicalFile: (id) => api.delete(`/admin/medical-files/${id}`),
  
  // 获取档案详情
  getMedicalFileDetail: (id) => api.get(`/admin/medical-files/${id}`),
  
  // 添加医疗文档
  addMedicalDocument: (fileId, data) => api.post(`/admin/medical-files/${fileId}/documents`, data),
  
  // 上传医疗文档
  uploadMedicalDocument: (fileId, file) => {
    const formData = new FormData()
    formData.append('document', file)
    return api.post(`/admin/medical-files/${fileId}/upload`, formData, {
      headers: { 'Content-Type': 'multipart/form-data' }
    })
  },
  
  // 导出档案
  exportMedicalFile: (id) => api.get(`/admin/medical-files/${id}/export`, { responseType: 'blob' }),
  
  // 打印档案
  printMedicalFile: (id) => api.get(`/admin/medical-files/${id}/print`, { responseType: 'blob' })
}

// 外出服务API（后台管理）
export const outingServiceAPI = {
  // 获取外出服务申请列表
  getOutingApplications: (params) => api.get('/admin/outing-services/applications', { params }),
  
  // 审核申请
  reviewApplication: (id, data) => api.put(`/admin/outing-services/applications/${id}/review`, data),
  
  // 分配服务人员
  assignWorker: (id, data) => api.put(`/admin/outing-services/applications/${id}/assign`, data),
  
  // 获取服务人员列表
  getWorkers: (params) => api.get('/admin/outing-services/workers', { params }),
  
  // 添加服务人员
  addWorker: (data) => api.post('/admin/outing-services/workers', data),
  
  // 更新服务人员
  updateWorker: (id, data) => api.put(`/admin/outing-services/workers/${id}`, data),
  
  // 删除服务人员
  deleteWorker: (id) => api.delete(`/admin/outing-services/workers/${id}`),
  
  // 获取统计数据
  getStatistics: () => api.get('/admin/outing-services/statistics'),
  
  // 导出数据
  exportData: (params) => api.get('/admin/outing-services/export', { 
    params, 
    responseType: 'blob' 
  })
}

// 通用API
export const commonAPI = {
  // 文件上传
  uploadFile: (file, type = 'general') => {
    const formData = new FormData()
    formData.append('file', file)
    formData.append('type', type)
    return api.post('/upload', formData, {
      headers: { 'Content-Type': 'multipart/form-data' }
    })
  },
  
  // 获取字典数据
  getDictionary: (type) => api.get(`/dictionary/${type}`),
  
  // 发送短信验证码
  sendSmsCode: (phone, type) => api.post('/sms/send', { phone, type }),
  
  // 验证短信验证码
  verifySmsCode: (phone, code, type) => api.post('/sms/verify', { phone, code, type })
}

export default api